<template>
  <!-- 系统变量 -->
  <!-- 顶部 搜索栏 -->
  <el-form :model="form" class="demo-form-inline" :inline="true">
    <el-form-item label="设备名称">
      <el-input v-model="seachValue.name" clearable />
    </el-form-item>
    <el-form-item label="设备类型">
      <el-cascader
        style="width: 100%"
        v-model="seachValue.DevicetypeValue"
        :options="options"
        :show-all-levels="false"
        clearable
        placeholder="请选择设备类型"
        :props="{ value: 'DevicetypeValue', label: 'DevicetypeName' }"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getSeachList">
        <el-icon><Search /></el-icon> 搜索
      </el-button>
      <el-button @click="rest">
        <el-icon><Refresh /></el-icon> 重置
      </el-button>
    </el-form-item>
  </el-form>

  <el-row :gutter="10">
    <el-col :span="1.5">
      <el-button type="primary" plain size="mini" @click="addDevice" :disabled="buttonshow">
        <el-icon><Plus /></el-icon> 新增变量
      </el-button>
    </el-col>
  </el-row>

  <!-- table 表格 -->
  <el-table
    ref="multipleTableRef"
    :data="tableData"
    style="width: 100%; margin-top: 10px"
    show-overflow-tooltip
  >
    <el-table-column type="selection" />
    <el-table-column property="name" label="变量名称" align="center" />
    <el-table-column label="变量类型" align="center">
      <template #default="scope">
        <div>{{ displayRuleText1(scope.row.SystemVariableType) }}</div>
      </template>
    </el-table-column>
    <el-table-column property="state" label="变量值" align="center">
      <template #default="scope">
        <div v-if="scope.row.SystemVariableType === 'EXPRESSION'">
          {{ displayRuleText(scope.row) }}
        </div>
        <div v-else>{{ scope.row.Expression }}</div>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-link :underline="false" @click="modify(scope.row)" style="margin-right: 10px">
          修改
        </el-link>
        <el-link :underline="false" @click="deldevice(scope.row.id)">删除</el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    style="float: right"
    v-model:currentPage="currentPage"
    :total="total"
    :page-size="pageSize"
    @current-change="handleCurrentChange"
  ></el-pagination>

  <AddDevice ref="adddeviceref" @update="updateList"></AddDevice>
  <ChangeSysVariable ref="ChangeSysVariable" @update="updateList"></ChangeSysVariable>
</template>

<script>
import { defineComponent, ref, onMounted, computed, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import until from './seach.js'
import AddDevice from './AddSystemVariable.vue'
import ChangeSysVariable from './ChangeSysVariable.vue'
import VirtualDevice from '../../MyJson/VirtualDevice.json'

export default defineComponent({
  components: {
    AddDevice,
    ChangeSysVariable
  },
  setup(_, { emit }) {
    const store = useStore()
    const seachValue = ref({ name: '', DevicetypeValue: '', isVirtual: 'IS_VARIABLE' })
    const page = ref(0)
    const pageSize = ref(10)
    const currentPage = ref(1)
    const total = ref(0)
    const totalPage = ref(0)
    const tableData = ref([])
    const options = ref(null)
    const multipleTableRef = ref(null)
    const adddeviceref = ref(null)
    const ChangeSysVariable = ref(null)

    const displayRuleText = computed(() => {
      return (judgeValue) => {
        if (judgeValue) {
          const deviceTypeStr = store.state.beforeAllDevice
          let name = ''
          const value = JSON.parse(judgeValue.dynamicTags)
          value.forEach((item) => {
            const cleanedInput = item.value.replace(/[{}]/g, '')
            const resultArray = cleanedInput.split('.')
            const dds = deviceTypeStr.filter(
              (item) =>
                item.id === resultArray[0] &&
                (item.DeviceVariable === 'AVAILABLE' ||
                  item.isVirtual === 'IS_VIRTUAL' ||
                  (item.ComPort && item.pid === '-1'))
            )
            if (resultArray[0] === '1234567890' || dds.length) {
              const res = window.api.getDeviceNameAndSystemParameterPropertyStatusName(
                resultArray[0],
                resultArray[1]
              )
              item.name = res
            } else {
              const res = window.api.getDeviceNameByDeviceTableId(resultArray[0], resultArray[1])
              if (res) {
                item.name = res
              }
            }
            name += item.name
          })
          return name
        }
      }
    })

    const displayRuleText1 = computed(() => {
      return (judgeValue) => {
        if (judgeValue) {
          const item = VirtualDevice.template[0].find((item) => judgeValue == item.value)
          return item ? item.name : ''
        }
      }
    })

    onMounted(() => {
      rest()
      const deviceTypeStr = store.state.deviceTypeStr
      const device = JSON.parse(JSON.stringify(deviceTypeStr))
      options.value = device.children.filter((item) => item.isVirtual === 'IS_VARIABLE')
    })

    const addDevice = () => {
      adddeviceref.value.openDialog(tableData.value)
    }

    const deldevice = (id) => {
      const res = window.api.removeDvcAndDvcVersion(id)
      if (res === '删除成功') {
        ElMessage.success('删除成功')
        rest()
      } else {
        ElMessage.error(res)
      }
    }

    const modify = (data) => {
      const device = JSON.parse(window.api.getDvcAndDvcVerById(data.id))
      const deviceTypeStr = store.state.beforeAllDevice

      device.dynamicTags.forEach((item) => {
        const cleanedInput = item.value.replace(/[{}]/g, '')
        const resultArray = cleanedInput.split('.')
        const dds = deviceTypeStr.filter(
          (item) =>
            item.id === resultArray[0] &&
            (item.DeviceVariable === 'AVAILABLE' ||
              item.isVirtual === 'IS_VIRTUAL' ||
              (item.ComPort && item.pid === '-1'))
        )
        if (resultArray[0] === '1234567890' || dds.length) {
          const res = window.api.getDeviceNameAndSystemParameterPropertyStatusName(
            resultArray[0],
            resultArray[1]
          )
          item.name = res
        } else {
          const res = window.api.getDeviceNameByDeviceTableId(resultArray[0])
          if (res) {
            item.name = res
          }
        }
      })
      ChangeSysVariable.value.openDialog(device, tableData.value)
    }

    const rest = () => {
      seachValue.value = { name: '', DevicetypeValue: '' }
      const res = until.seachList({ isVirtual: 'IS_VARIABLE' }, page.value, pageSize.value)
      newlist(res)
      let deviceRes = JSON.parse(window.api.listDvcAndDvcVer())
      store.commit('beforeAllDeviceupdate', deviceRes)
      deviceRes = null
    }

    const handleCurrentChange = (newPage) => {
      page.value = newPage - 1
      getSeachList()
    }

    const getSeachList = () => {
      let seachchange = { isVirtual: 'IS_VARIABLE' }
      if (seachValue.value.name && !seachValue.value.DevicetypeValue) {
        seachchange.name = seachValue.value.name
      }
      if (!seachValue.value.name && seachValue.value.DevicetypeValue) {
        const num = seachValue.value.DevicetypeValue[seachValue.value.DevicetypeValue.length - 1]
        seachchange.DevicetypeValue = num
      }
      const res = until.seachList(seachchange, page.value, pageSize.value)
      newlist(res)
    }

    const newlist = (res) => {
      tableData.value = res.Searchlistres.filter((item) => item.isVirtual === 'IS_VARIABLE')
      store.commit('getNewvariableList', JSON.parse(JSON.stringify(tableData.value)))
      currentPage.value = res.totalList.currentPage
      pageSize.value = res.totalList.pageSize
      total.value = res.totalList.total
      totalPage.value = res.totalList.totalPage
    }

    const updateList = () => {
      rest()
    }

    onBeforeUnmount(() => {
      page.value = 0
      pageSize.value = 10
      currentPage.value = 1
      total.value = 0
      totalPage.value = 0
      tableData.value = []
      options.value = null
    })

    return {
      tableData,
      options,
      multipleTableRef,
      adddeviceref,
      seachValue,
      currentPage,
      total,
      pageSize,
      rest,
      getSeachList,
      handleCurrentChange,
      addDevice,
      deldevice,
      modify,
      displayRuleText,
      displayRuleText1,
      updateList,
      ChangeSysVariable
    }
  }
})
</script>

<style scoped>
.demo-form-inline .el-form-item {
  margin-right: 10px;
}
</style>
